package com.application.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;


import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;

import ReadWriteXML.CMember;
import android.app.AlertDialog;
import android.app.LocalActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.Toast;


public class FrmTabActivity  extends TabActivity{
	public static int ON_EXIT_APP=1111;
	//-=====Truc====
	public static Runnable raShowTeacherLogout;
	///
	public static int CODE_KICK = 101;
	public static int CODE_CHATPEER = 401;
	public static String IP_CHATPEER = "IP_CHATPEER";
	public static int CODE_CHAT = 201;
	public static int CODE_STOP_TALK = 301;
	public static String IP_RESULT = "IP_RESULT";
	public static Handler handler = new Handler();
	public static Context baseContext;
	public static String contentTitle, contentText;
	public static String message;
	public static Runnable showMessage;
	public static int kickVoteResult;
	public static Address ipBeingKick;
	public static Address ipBeingStopTalk;
	public static int timeVoteKick;
	int timeStopTalk;
	ArrayList<CMember> memberList;
	public static ArrayList<Integer> yesVote;
	public static ArrayList<Integer> noVote;
	public static Runnable dislayKickMember;
	public static Runnable dislayKickedMessage;
	public static Runnable reLoadTabTree;
	public static Runnable raMoiVaoNhomNotif;
	static String loi = "";
	public static Runnable raShowMessage;
	LocalActivityManager localActivity;
	//PingThread t;
	private TabHost mTabHost;
	private Context mTabHostContext;
	private View surfaceView1, surfaceView2;
	
	//chat rieng
	
	public static String ipSender;
	public static String userNameSender;
	public static Runnable showFormChatPeer;
	public static Runnable showFormChatPeerNonParamater;
	//=========end Truc===========
	private static TabHost _tabHost;
	private static Context _cont;
	private static int _tabIndex = 1;
	private static final int NOTEPAD = Menu.FIRST+3;
	private static final int INTERACTION = Menu.FIRST+4;
	private static final int SETTING = Menu.FIRST+5;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    requestWindowFeature(Window.FEATURE_NO_TITLE);
	    setContentView(R.layout.tab_holder);
	    
	    _cont = this;
	    Resources res = getResources(); // Resource object to get Drawables
	    set_tabHost(getTabHost());  // The activity TabHost
	    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
	    Intent intent;  // Reusable Intent for each tab

	    // Initialize a TabSpec for each tab and add it to the TabHost
	    intent = new Intent().setClass(this, StackActivity.class);
	    spec = get_tabHost().newTabSpec("subject").setIndicator("Học tập",
	                      res.getDrawable(R.drawable.ic_tab_subject))
	                  .setContent(intent);
	    get_tabHost().addTab(spec);
	//====old======================    
//	    intent = new Intent().setClass(this, FrmConversation.class);
//	    spec = get_tabHost().newTabSpec("conversation").setIndicator("Thảo luận",
//	                      res.getDrawable(R.drawable.ic_tab_chat))
//	                  .setContent(intent);
//	    get_tabHost().addTab(spec);
//
//	    // Do the same for the other tabs
//	    intent = new Intent().setClass(this, FrmInviteGroupChat.class);
//	    spec = get_tabHost().newTabSpec("userlist").setIndicator("Danh sách lớp",
//	                      res.getDrawable(R.drawable.ic_tab_userlist))
//	                  .setContent(intent);
//	    get_tabHost().addTab(spec);
//	

//	    get_tabHost().getChildAt(0).setOnClickListener(new OnClickListener() {
//	        @Override
//			public void onClick(View v) {
//	            getTabHost().setCurrentTab(0);
//	        }
//	    });
	    //=====end old==================
	    
	    //======TRUC======================
	    
	    
	    intent = new Intent().setClass(this, frmTaoNhom.class);
	    spec = get_tabHost().newTabSpec("taonhom").setIndicator("Tạo nhóm",
	                      res.getDrawable(R.drawable.ic_tab_chat))
	                  .setContent(intent);
	    get_tabHost().addTab(spec);
	    //=====
	    raShowTeacherLogout=new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				ShowMessageTeacherLogout();
			}
		};
	    
	    //======
	    showFormChatPeer = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ShowChatPeerForm(ipSender,userNameSender);
			}
		};
		
		dislayKickMember = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HienThiMHBieuQuyetKick();
			}
		};

		dislayKickedMessage = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ShowMessageKicked();
			}
		};
	    
	    reLoadTabTree=new Runnable() {
			
			@Override
			public void run() {
				ReLoadTabWithTree();
			}
		};
	    raMoiVaoNhomNotif = new Runnable() {

			@Override
			public void run() {
				if (kiemTraVaoNhom()) {
					displayNotification("Có người mời bạn vào nhóm!", contentText, contentTitle);
				}
			}
		};
		raShowMessage = new Runnable() {
			 
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Show(loi);
			}
		};
		showMessage = new Runnable() {
			 
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Show(message);
			}
		};
		//=============END TRUC==================================
	}
	
	///=============TRUC========
	
	public void ShowMessageTeacherLogout(){
		Log.v("Phu","vao ham ShowMessageTeacherLogout tabACt");
		Log.e("Phu", "activity class = "+ActivityController.getPeerActivity().getLocalClassName());
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo")
		.setCancelable(false).setMessage("Giáo viên đã rời khỏi hệ thống.")//.setIcon(R.drawable.img_dialog)
		
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.v("Phu","vao onclick");
				NetworkController.peerRelease();
				Log.v("PEERDROID","Đã Thoát khỏi chương trình");
				finish();
				System.exit(0);
			}
		}).create();
		Log.v("Phu","1");
		dlg.show();
		
		Log.v("Phu","2");
	}
	public void ShowMessageKicked() {
		// Toast.makeText(this, "hehe Xin chao", Toast.LENGTH_SHORT).show();
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo").setMessage("Bạn đã bị mời ra khỏi nhóm.")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if(!NetworkController.isOffline())
						{
							String s = NetworkController.get_ipHost();
							NetworkController.SendMessageLogout();
//							NetworkController.peerRelease();
							//xoá danh sách hàng xóm khi thoát khỏi ứng dụng
//							ReadWriteFileController.deleteFile(ReadWriteFileController.pathNeighborsList);
							
						}
						//NetworkController.SendMessageLogout(new Address("192.168.173.20:5033"));
						Log.d("PEERDROID","Đã Thoát khỏi chương trình");
						finish();
						//NetworkController.CloseDiscussActivity();
					}
				}).create();
		dlg.show();
	}

	public void HienThiMHBieuQuyetKick() {
		Log.d("Phu", "vao ham HienThiMHBieuQuyetKick");
		Intent i = new Intent(this.getBaseContext(), frmBieuQuyetMoiRoiNhom.class);
		startActivity(i);
	}

	public void ShowChatPeerForm(String ipReceiver,String userName) {
//		Intent i = new Intent(this, frmChatPeerActivity.class);
//		startActivity(i);
		Intent data=new Intent(this,frmChatPeerActivity.class);
		data.putExtra(frmChatPeerActivity.IP_CHAT_PEER, ipReceiver);
		data.putExtra(frmChatPeerActivity.USERNAME, userName);
		setResult(frmChatPeerActivity.CODE_CHATPEER, data);
		
		
		startActivity(data);
	}
	
	public void Show(String message) {
		Log.v("Phu","in Show message trong TabActivity");
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo").setMessage(message)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				}).create();
		dlg.show();
	}
	
	public void showMessage(String message) {

		AlertDialog alert = new AlertDialog.Builder(this).create();
		alert.setMessage(message);
		alert.setTitle("Thông báo");
		alert.show();
	}
	private boolean kiemTraVaoNhom() {
		return true;
	}
	public void displayNotification(String tickerText, String contentTitle, String contentText) {

		Log.i("Phu","trong displayNotification:   "+tickerText+" : "+contentText+" : "+contentTitle);
		
		Intent intent = new Intent(getApplicationContext(), frmNotificationMoiVaoNhom.class);
		Log.i("Phu","qua khoi tao Intent");
		intent.putExtra("ID", 1);
		intent.putExtra("tickerText", tickerText);
		intent.putExtra("contentTitle", contentTitle);
		intent.putExtra("contentText", contentText);
		Log.i("Phu","qua Intent rui");
	
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.ic_launcher, tickerText, System.currentTimeMillis());
		String[] m = contentText.split("#~");
		Log.i("Phu","vao Pending Intent ");
		notif.setLatestEventInfo(this, m[0] + " mời bạn vào nhóm!", contentTitle, pendingIntent);
		notif.flags|=Notification.FLAG_AUTO_CANCEL;
		notif.when=1;
		notiManager.notify(1, notif);
		
	}

	public void ReLoadTabWithTree(){
		
		get_tabHost().clearAllTabs();
		 _cont = this;
		    Resources res = getResources(); // Resource object to get Drawables
		   // set_tabHost(getTabHost());  // The activity TabHost
		    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
		    Intent intent;  // Reusable Intent for each tab

		    // Initialize a TabSpec for each tab and add it to the TabHost
		    intent = new Intent().setClass(getBaseContext(), StackActivity.class);
		    spec = get_tabHost().newTabSpec("subject").setIndicator("Học tập",
		                      res.getDrawable(R.drawable.ic_tab_subject))
		                  .setContent(intent);
		    get_tabHost().addTab(spec);
		    
		    intent = new Intent().setClass(getBaseContext(), frmTreeNodeActivity.class);
		    spec = get_tabHost().newTabSpec("caythaoluan").setIndicator("Cây thảo luận",
		                      res.getDrawable(R.drawable.ic_tab_chat))
		                  .setContent(intent);
		    get_tabHost().addTab(spec);
		    get_tabHost().setCurrentTab(0);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("Phu", " vao ham onActivityResult tab");
		Log.d("Phu", "resultCode= " + resultCode);
		if (resultCode == CODE_KICK) {
			Log.d("Phu", " CODE_KICK");
			String ipKick = data.getStringExtra(IP_RESULT);
			if (ipKick != null) {
				// userNameKick = data.getStringExtra(USERNAME_BEING_KICK);
				ShowSetTimeVoteKick(ipKick);

			}
		}
		 if (resultCode == ON_EXIT_APP) {
			 finish();
		 }
		if (resultCode == CODE_STOP_TALK) {
			Log.d("Phu", " CODE_STOP_TALK");
			String ipStop = data.getStringExtra(IP_RESULT);
			if (ipStop != null) {
				// userNameStop = data.getStringExtra(USERNAME_STOP_TALK);
				ShowSetTimeStopTalking(ipStop);
			}
		}
	}
	public void ShowSetTimeVoteKick(final String IP) {

		Log.d("Phu", " vao ShowSetTimeVoteKick");
		Log.d("Phu", "ip kick" + IP);
		Log.d("Phu", "My ip " + NetworkController._peer.getAddressPeer());
		String s[] = IP.split(":");
 
		String ipBeKick = s[1] + ":" + s[2];
		Log.d("Phu", "ip be kick " + ipBeKick);
		if (NetworkController._peer.getAddressPeer().equals(ipBeKick)) {
			NetworkController.ShowMessageNoticeTAB("Bạn không thể làm điều này!");
		} else {
			final EditText txtTime = new EditText(this);
			txtTime.setSingleLine();
			txtTime.setInputType(2);
			AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Chọn thời gian biểu quyết")
					.setMessage("Thời gian được tính bằng giây.").setView(txtTime)
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							String StrTime = txtTime.getText().toString();
							int time = Integer.parseInt(StrTime);
							timeVoteKick = time;
							yesVote = new ArrayList<Integer>();
							noVote = new ArrayList<Integer>();
							ipBeingKick = new Address(IP);
					//		memberList = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
//							for (CMember member : memberList) {
//								NetworkController.SendVoteKickMember(new Address(member.get_ip()), ipBeingKick, time);
//							}
							NetworkController.SendVoteKickMemberGroup("TRUC", ipBeingKick, time);
							Log.d("Phu", "Da gui xong kick");
							// dem thoi gian
							long kickTime = timeVoteKick * 1000;

							CountDownTimer timer = new CountDownTimer(kickTime, 1000) {
								@Override
								public void onTick(long millisUntilFinished) {

								}

								@Override
								public void onFinish() {
									Toast.makeText(getBaseContext(), "het gio kick", Toast.LENGTH_SHORT).show();
									Log.w("Phu", "yes size="+yesVote.size());
									Log.w("Phu", "no size="+noVote.size());
									kickVoteResult = 0;
									if (yesVote.size() != 0 || noVote.size() != 0) {
										
										if (yesVote.size() >= noVote.size()) {
											kickVoteResult = 1;
										}
										memberList = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
										for (CMember member : memberList) {
											Log.d("Phu", "gui result toi " + member.get_ip());
											NetworkController.SendResultVoteKickMember(new Address(member.get_ip()),
													kickVoteResult, ipBeingKick);
										}
									} else {
										// NetworkController.ShowMessageNotice("Không có ai tham gia biểu quyết.");
										NetworkController.ShowMessageNoticeTAB("Không có ai tham gia biểu quyết.");
										memberList = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
										for (CMember member : memberList) {
											Log.d("Phu", "gui result toi " + member.get_ip());
											NetworkController.SendResultVoteKickMember(new Address(ipBeingKick),
													kickVoteResult, ipBeingKick);
										}
									}
								}
							}.start();
						}
					}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

						}
					}).create();
			dlg.show();
		}
	}
	
	public void ShowSetTimeStopTalking(final String ipStop) {
		final EditText txtTimeTalk = new EditText(this);
		txtTimeTalk.setSingleLine();
		txtTimeTalk.setInputType(2);
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Chọn thời gian buộc ngừng thảo luận")
				.setMessage("Thời gian được tính bằng giây.").setView(txtTimeTalk)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String StrTime = txtTimeTalk.getText().toString();
						int time = Integer.parseInt(StrTime);
						timeStopTalk = time;
						ipBeingStopTalk = new Address(ipStop);
						NetworkController.GuiYeuCauNgungThaoLuan(ipBeingStopTalk, time);
						Log.d("Phu", "vao onclick ngung noi");
						long timeLong = timeStopTalk * 1000;
						Toast.makeText(getBaseContext(), timeLong + "", 1).show();
						CountDownTimer timer = new CountDownTimer(timeLong, 1000) {

							@Override
							public void onTick(long millisUntilFinished) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onFinish() {
								// TODO Auto-generated method stub
								
								NetworkController.GuiChoPhepThaoLuan(ipBeingStopTalk);
							}
						}.start();
					}

				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				}).create();
		dlg.show();
	}
	
	//=======END TRUC======
	@Override
	protected void onStart(){
		super.onStart();
		ActivityController.setPeerActivity(this);
		ActivityController.addActivityToArray(this);
	}
	@Override
	public void onPause(){
		super.onPause();
		ActivityController.setPeerActivity(this);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		ActivityController.setPeerActivity(this);
		Log.d("PEERDROID","vao onresume tab host");
		Log.d("PEERDROID","tabIndex: " + _tabIndex);
		switch (_tabIndex) {
		case 0:
			get_tabHost().setCurrentTabByTag("subject");
			break;
		case 1:
			get_tabHost().setCurrentTabByTag("conversation");
			break;
		case 2:
			get_tabHost().setCurrentTabByTag("userlist");
			break;
		}
			
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
//	new MenuInflater(getApplication()).inflate(R.menu.omnu_thao_luan, menu);
		
		menu.add(Menu.NONE, NOTEPAD, Menu.NONE, "Note")
		.setIcon(R.drawable.img_clear)
		.setAlphabeticShortcut('e');
		menu.add(Menu.NONE, INTERACTION, Menu.NONE, "Cộng tác")
		.setIcon(R.drawable.img_cauhoi)
		.setAlphabeticShortcut('f');
		menu.add(Menu.NONE, SETTING, Menu.NONE, "Tuỳ chỉnh")
		.setIcon(R.drawable.img_chat)
		.setAlphabeticShortcut('g');
		return(super.onCreateOptionsMenu(menu));
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case NOTEPAD:
			startActivity(new Intent(this, FrmNote.class));
			return(true);
		case INTERACTION:
			startActivity(new Intent(this, FrmInteraction.class));
			return(true);
		case SETTING:
			startActivity(new Intent(this, PrefSetting.class));
//		case R.id.mnuDanhSachThanhVien:
//			Intent iDanhSachThanhVien = new Intent(getBaseContext(), frmDanhSachThanhVienActivity.class);
//			startActivityForResult(iDanhSachThanhVien, CODE_KICK);
//			break;
//		case R.id.mnuChiaSeTaiLieu:
//			Toast.makeText(getBaseContext(), "Chia sẻ tài liệu", 1).show();
//			break;
//		case R.id.mnuVaoTroCuaToi:
//			Intent iVaiTro = new Intent(getBaseContext(), frmVaiTroCuaToiActivity.class);
//			startActivity(iVaiTro);
//			break;
//		case R.id.mnuQuyenCuaToi:
//			Intent iQuyen = new Intent(getBaseContext(), frmQuyenCuaToi.class);
//			startActivity(iQuyen);
//			break;
//		default:
//			break;
			return(true);
		}
		
		return super.onOptionsItemSelected(item);
	}
	public static void set_tabHost(TabHost _tabHost) {
		FrmTabActivity._tabHost = _tabHost;
	}
	public static TabHost get_tabHost() {
		return _tabHost;
	}
	public static void setTabIndex(int tabIndex) {
		_tabIndex = tabIndex;
	}
	public static int getTabIndex() {
		return _tabIndex;
	}
	
}
